package cn.lili.modules.serviceimpl;

import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.client.ShortLinkClient;
import cn.lili.modules.message.entity.dos.ShortLink;
import cn.lili.modules.service.TicketService;
import com.alibaba.fastjson.JSON;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TicketServiceImpl implements TicketService {

    @Autowired
    private UserApi userApi;

    @Autowired
    private ShortLinkClient shortLinkClient;

    @Override
    public ResultMessage<Object> generateShareSign(String scene) {
        //短链接存储
        ShortLink shortLink = new ShortLink();
        shortLink.setOriginalParams(scene);
        List<ShortLink> shortLinks = shortLinkClient.queryShortLinks(shortLink);
        if (!shortLinks.isEmpty()) {
            shortLink = shortLinks.get(0);
        } else {
            shortLink.setOriginalParams(scene);
            shortLinkClient.save(shortLink);
            shortLink = shortLinkClient.queryShortLinks(shortLink).get(0);
        }

        Map<String, String> res = new HashMap<>();
        String nonce = IdWorker.getIdStr();
        long millis = System.currentTimeMillis();
        String sign = userApi.generateShareSign(nonce, millis);
        log.info("----sign--{}",sign);
        res.put("nonce", nonce);
        res.put("timestamp", String.valueOf(millis));
        res.put("sign", sign);
        res.put("scene", shortLink.getId());
        log.info("----res--{}", JSON.toJSONString(res));
        return ResultUtil.data(res);
    }
}
